<template>
  <ul class="star-wrap">
    <li v-for="(item, index) of itemClasses"
        :key="index"
        :class="item">
    </li>
  </ul>
</template>

<script>
export default {
  name: 'CommonStar',
  props: {
    score: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      LENGTH: 5,
      CLS_ON: 'on',
      CLS_HALF: 'half',
      CLS_OFF: 'off',
      REG: /\d+\.(\d*)/
    }
  },
  computed: {
    itemClasses () {
      let result = []
      // 小数点之后的数字,用于判断是全星还是半星
      let allStar = this.score.toString().replace(this.REG, '$1')

      // 取整数
      let score = Math.floor(this.score * 2) / 2
      // 判断半星
      let hasDecimal = score % 1 !== 0

      let integer = Math.floor(score)
      // 4.8以上为5星
      if (allStar && Number(allStar) >= 8) {
        hasDecimal = false
        integer += 1
      }
      for (let i = 0; i < integer; i++) {
        result.push(this.CLS_ON)
      }
      if (hasDecimal) {
        result.push(this.CLS_HALF)
      }
      // 没有星星
      while (result.length < this.LENGTH) {
        result.push(this.CLS_OFF)
      }
      return result
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~stylus/mixins.styl'

.star-wrap
  display flex
  height 40px
  align-items center

  .on
    width 20px
    height 20px
    margin-right 2px
    bgckImg('~@/assets/images/star.png', 0, 0px)

  .half
    width 20px
    height 20px
    margin-right 2px
    bgckImg('~@/assets/images/star.png', 0, -19.8px)

  .off
    width 20px
    height 20px
    margin-right 2px
    bgckImg('~@/assets/images/star.png', 0, -38.5px)
</style>
